<template>
  <div class="typing-content">
    <div class="typing-inner">
      <span v-html="displayText"></span>
      <span v-if="isTyping" class="typing-cursor">|</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, onMounted } from 'vue';
  const props = defineProps({
    text: { type: String, required: true },
    speed: { type: Number, default: 100 },
    delay: { type: Number, default: 100 },
  });

  const displayText = ref('');
  const isTyping = ref(false);
  let typingTimer: NodeJS.Timeout | null = null;

  const startTyping = () => {
    if (typingTimer) clearInterval(typingTimer);

    displayText.value = '';
    isTyping.value = true;

    // setTimeout(() => {
    let index = 0;
    const text = props.text;

    typingTimer = setInterval(() => {
      if (index < text.length) {
        const char = text.charAt(index);
        // 关键：将换行符\n转换为<br>标签
        displayText.value += char === '\n' ? '<br>' : char;
        index++;
      } else {
        clearInterval(typingTimer!);
        isTyping.value = false;
      }
    }, props.speed);
    // }, props.delay);
  };

  onMounted(() => startTyping());

  // 监听文本变化，重新触发打字
  watch(
    () => props.text,
    (newVal) => newVal !== displayText.value.replace(/<br>/g, '\n') && startTyping()
  );

  // 监听速度和延迟变化
  watch(
    () => [props.speed, props.delay],
    () => isTyping.value && startTyping()
  );
</script>

<style scoped>
  .typing-content {
    font-size: 14px;
    line-height: 1.8;
    min-height: 80px;
    padding: 16px;
    border-radius: 4px;
    margin-bottom: 20px;
    font-family: 'Courier New', monospace;
    background-color: transparent !important;
    white-space: pre-line; /* 可选：增强换行显示效果 */
    display: flex;
    align-items: center;
  }

  .typing-inner {
    display: inline-block;
  }

  .typing-cursor {
    animation: blink 0.7s infinite;
    margin-left: 2px;
    vertical-align: baseline;
  }

  @keyframes blink {
    0%,
    100% {
      opacity: 1;
    }
    50% {
      opacity: 0;
    }
  }
</style>
